/**
 * @author zhuo
 */

function CanvasLayer(options) {
  this.options = options || {};
  this.context = this.options.context || "2d";
  this.zIndex = this.options.zIndex || 0;
  this._map = options.map;
  // var c = this.initialize(this._map);
  // var ctx = c.getContext("2d");
  // ctx.fillStyle = "#ff0000";
  // ctx.fillRect(0, 0, 150, 75);
  this.show();
}
var global = typeof window === "undefined" ? {} : window;
var BMap = global.BMap || global.BMapGL;
if (BMap) {
  // canvaslayer属性基础至bmap.overlay
  CanvasLayer.prototype = new BMap.Overlay();

  // 设置初始化方法 bmap源码中可能在控制自动执行initialise画布方法，不初始化会报错,mapv源码中并没有调用此方法
  CanvasLayer.prototype.initialize = function(map) {
    this._map = map;
    var canvas = (this.canvas = document.createElement("canvas"));
    canvas.style.cssText =
      "positiion: absolute;" +
      "left: 0;" +
      "top: 0;" +
      "z-index:" +
      this.zIndex +
      ";user-select:none;";
    this.adjustSize();
    var pane = map.getPanes().floatShadow;
    pane.appendChild(canvas);
    var that = this;
    map.addEventListener("resize", function() {
      that.adjustSize();
      that._draw();
    });
    map.addEventListener("update", function() {
      that._draw();
    });
    return this.canvas;
  };

  CanvasLayer.prototype.show = function() {
    if (!this.canvas) {
      this._map.addOverlay(this);
    }
    this.canvas.style.display = "block";
  };
  // 调整canvas尺寸
  CanvasLayer.prototype.adjustSize = function() {
    var size = this._map.getSize();
    var canvas = this.canvas;

    var devicePixelRatio = (this.devicePixelRatio =
      global.devicePixelRatio || 1);

    canvas.width = size.width * devicePixelRatio;
    canvas.height = size.height * devicePixelRatio;
    if (this.context == "2d") {
      canvas.getContext(this.context).scale(devicePixelRatio, devicePixelRatio);
    }

    canvas.style.width = size.width + "px";
    canvas.style.height = size.height + "px";
  };
  // 知道为什么有个draw了，这个也时bmap.overlay源码里的方法，在mapV这里重写了
  CanvasLayer.prototype.draw = function() {
    var self = this;
    self._draw();
  };
  CanvasLayer.prototype._draw = function() {
    var map = this._map;
    var size = map.getSize();
    var center = map.getCenter();
    if (center) {
      var pixel = map.pointToOverlayPixel(center);
      this.canvas.style.left = pixel.x - size.width / 2 + "px";
      this.canvas.style.top = pixel.y - size.height / 2 + "px";
      // 怪不得mapV源码里没创建这个事件，这个估计在bmap里创建的，这个mapvbaidulayer依附于bmap源码，类似于bmap的插件
      this.dispatchEvent("draw");
      this.options.update && this.options.update.call(this);
    }
  };
  CanvasLayer.prototype.setZIndex = function(zIndex) {
    this.zIndex = zIndex;
    this.canvas.style.zIndex = this.zIndex;
  };
}

export default CanvasLayer;
